package com.hmall.item.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.dto.PageDTO;
import com.hmall.item.mapper.ItemMapper;
import com.hmall.item.pojo.Item;
import com.hmall.item.service.IItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ItemService extends ServiceImpl<ItemMapper, Item> implements IItemService {

    @Autowired
    private ItemMapper itemMapper;

    /**
     * 分页查询
     * @param page
     * @param size
     * @return
     */
    @Override
    public PageDTO<Item> getList(Integer page, Integer size) {
        Page<Item> pagesize = new Page<>(page, size);
        itemMapper.selectPage(pagesize, null);
        List<Item> records = pagesize.getRecords();
        long total = pagesize.getTotal();
        return new PageDTO<Item>(total, records);
    }

    /**
     * 根据id查找
     * @param id
     * @return
     */
    @Override
    public Item getItem(Integer id){
        Item item = itemMapper.selectById(id);
        return item;
    }

    /**
     * 新增
     * @param item
     * @return
     */
    @Override
    public boolean save(Item item) {
        item.setStatus(2);
        int insert = itemMapper.insert(item);
        if (insert>0){
            return true;
        }
        return false;
    }

    /**
     * 修改商品状态
     * @param id
     * @param status
     * @return
     */
    @Override
    public boolean setStatus(Integer id, Integer status) {
        int i = itemMapper.setStatus(id, status);
        return true;
    }

    /**
     * 修改商品信息
     * @param item
     * @return
     */
    @Override
    public boolean updateItem(Item item) {
        int i = itemMapper.updateById(item);
        return true;
    }

    /**
     * 修改商品库存
     * @param id
     * @param num
     */
    @Override
    public void stock(long id,Integer num){
        Item item = itemMapper.selectById(id);
        if (item.getStock()>num){
            item.setStock(item.getStock()-num);
            itemMapper.updateById(item);
        }else {
            log.error("库存不足");
        }

    }

    /**
     * 删除
     * @param id
     * @return
     */

    @Override
    public boolean delete(Integer id) {
        int i = itemMapper.deleteById(id);
        return true;
    }


}
